import { fileURLToPath } from 'url';
import nunjucks from 'nunjucks';
import fs from 'fs';
import { ConfigNunjucks } from "../config/setting.js";

export const registryTemplate = function () {
    return async (ctx, next) => {
        ctx.render = function (html, obj) {
            let currentFileUrl = import.meta.url;
            // console.log(currentFileUrl);

            let htmlBaseUrl = new URL(ConfigNunjucks, currentFileUrl);
            let htmlBasePath = fileURLToPath(htmlBaseUrl);

            let env = nunjucks.configure(htmlBasePath, { noCache: true, watch: true });
            ctx.body = env.render(html, obj)

        }

        await next()
    }
}


export const processStaticResources = function () {
    return async (ctx, next) => {
        let url = ctx.request.url;

        if (url.startsWith('/statics')) {
            ctx.body = fs.readFileSync(`../${url}`);
        }

        console.log(url);
        await next();
    }
}